//
//  LazyProperty.swift
//  EasyCoding
//
//  Created by JY_NEW on 2020/6/4.
//

import Foundation

///懒加载
@propertyWrapper
public enum PWLazy<Value> {
    case uninitialized(() -> Value)
    case initialized(Value)
    
    public init(wrappedValue: @autoclosure @escaping () -> Value) {
        self = .uninitialized(wrappedValue)
    }
    
    public var wrappedValue: Value {
        mutating get {
            switch self {
            case .uninitialized(let initializer):
                let value = initializer()
                self = .initialized(value)
                return value
            case .initialized(let value):
                return value
            }
        }
        set {
            self = .initialized(newValue)
        }
    }
    /// 可通过该值避免触发加载动作，可通过$变更名访问
    public var projectedValue: Value? {
        switch self {
        case .uninitialized(_):
            return nil
        case .initialized(let value):
            return value
        }
    }
    /// 是否已初始化
    public var isInitialized: Bool {
        switch self {
        case .uninitialized(_): return false
        case .initialized(_): return true
        }
    }
}
